<template>
  <div>
    <NavBar>
      <template v-slot:default>商品分类</template>
    </NavBar>
    <!-- 返回顶部 -->
    <back-top @bTop="bTop" v-show="isTabFix" />
    <div id="mainbox">
      <!-- 侧边栏 -->
      <van-sidebar class="leftmenu" v-model="activeKey">
        <van-collapse v-model="activeName" accordion>
          <van-collapse-item v-for="item in categories" :key="item.id" :title="item.name" :name="item.name" :disabled="!item.children.length">
            <van-sidebar-item v-for="k in item.children" :key="k.id" :title="k.name" @click="getGoods(k.id)" />
          </van-collapse-item>
        </van-collapse>
      </van-sidebar>
      <!-- 列表 -->
      <div class="goodslist">
        <!-- tabBar -->
        <div class="ordertab">
          <van-tabs v-model="active" @click="ordTabClick">
            <van-tab v-for="(item, index) in ordertabList" :title="item" :key="index"></van-tab>
          </van-tabs>
        </div>
        <!-- 商品列表 -->
        <div class="wrapper" v-show="showGoods.length">
          <div class="content">
            <van-card v-for="item in showGoods" :key="item.id" :num="item.comments_count" :tag="item.comments_count > 0 ? '流行': '热卖'" :price="item.price" :desc="item.updated_at.slice(0,10)" :title="item.title" :thumb="item.cover_url" origin-price="77.00" lazy-load @click="goDetail(item.id)" />=
          </div>
        </div>
        <div class="list-item" v-show="!showGoods.length">
          <img class="nullData" src="~assets/images/nullData.jpeg" alt="">
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { onMounted, ref, reactive, computed, watchEffect, nextTick } from "vue";
import NavBar from "components/common/navbar/NavBar";
import BackTop from "components/common/backtop/BackTop";
import { getCategory, getCategoryGoods } from "network/category.js";
import BScroll from "better-scroll";
import { useRouter } from "vue-router";

export default {
  setup() {
    const router = useRouter();
    let bscroll = reactive({});
    const ordertabList = ref(["销量排序", "价格排序", "评论排序"]);
    let activeKey = ref(-1);
    let activeName = ref("1");
    let active = ref(2);
    let categories = ref([]); // 分类列表
    let currentOrd = ref("sales"); // 当前排序
    let currentCid = ref(0); // 当前分类id
    let isTabFix = ref(false);

    // 商品列表数据模型
    const goods = reactive({
      sales: { page: 1, list: [], load: true },
      price: { page: 1, list: [], load: true },
      comments_count: { page: 1, list: [], load: true },
    });

    let showGoods = computed(() => {
      return goods[currentOrd.value].list;
    });

    const init = () => {
      getCategoryGoods({ category_id: currentCid.value, type: "sales" }).then(
        (res) => {
          goods.sales.list = res.goods.data;
          nextTick(() => {
            bscroll && bscroll.refresh();
            bscroll && bscroll.finishPullUp();
          });
        }
      );
      getCategoryGoods({ category_id: currentCid.value, type: "price" }).then(
        (res) => {
          goods.price.list = res.goods.data;
          nextTick(() => {
            bscroll && bscroll.refresh();
            bscroll && bscroll.finishPullUp();
          });
        }
      );
      getCategoryGoods({
        category_id: currentCid.value,
        type: "comments_count",
      }).then((res) => {
        goods.comments_count.list = res.goods.data;
        nextTick(() => {
          bscroll && bscroll.refresh();
          bscroll && bscroll.finishPullUp();
        });
      });
    };

    onMounted(async () => {
      await getCategory().then((res) => {
        categories.value = res.categories;
      });

      init();

      // 创建BScroll对象
      bscroll = new BScroll(document.querySelectorAll(".wrapper")[0], {
        probeType: 3, // 0 1 2 3.只要在运动就触发事件
        click: true, // 允许点击
        pullUpLoad: true, // 上拉加载更多
      });

      // 滚动触发事件
      bscroll.on("scroll", (position) => {
        isTabFix.value = -position.y > 300;
      });

      // 上拉加载
      bscroll.on("pullingUp", async () => {
        console.log("上拉加载");
        console.log(
          `当前类型：${currentOrd.value}, 当前状态：${
            goods[currentOrd.value].load
          }`
        );
        if (!goods[currentOrd.value].load) return;

        const page = goods[currentOrd.value].page + 1;
        await getCategoryGoods({
          category_id: currentCid.value,
          type: currentOrd.value,
          page,
        }).then((res) => {
          goods[currentOrd.value].list.push(...res.goods.data);
          goods[currentOrd.value].page += 1;
          if (res.goods.data.length == 0) goods[currentOrd.value].load = false;
        });

        bscroll.finishPullUp(); // 结束上拉加载行为

        bscroll.refresh();
      });
    });

    // 排序点击事件
    const ordTabClick = async (index) => {
      let ords = ["sales", "price", "comments_count"];
      currentOrd.value = ords[index];
      console.log("当前ord: ", ords[index], "分类id:", currentCid.value);
      nextTick(() => {
        bscroll && bscroll.refresh();
        bscroll && bscroll.finishPullUp();
      });
    };

    // 左侧菜单
    const getGoods = (id) => {
      currentCid.value = id;
      let ords = ["sales", "price", "comments_count"];
      ords.map((item) => {
        goods[item].load = true;
        goods[item].page = 1;
      });
      console.log("当前ord:", currentOrd.value, "分类id:", id);

      init();
    };

    const bTop = () => {
      bscroll.scrollTo(0, 0, 500);
    };

    const goDetail = (id) => {
      router.push({
        path: "/detail",
        query: {
          id,
        },
      });
    };

    return {
      activeKey,
      categories,
      activeName,
      active,
      ordertabList,
      ordTabClick,
      getGoods,
      currentOrd,
      currentCid,
      showGoods,
      bTop,
      isTabFix,
      goDetail,
    };
  },
  components: {
    NavBar,
    BackTop,
  },
};
</script>

<style lang="scss">
#mainbox {
  margin-top: 46px;
  height: calc(100vh - 46px);
  padding-bottom: 56px;
  display: flex;
  .leftmenu {
    width: 140px;
  }
  .goodslist {
    flex: 1;
    .ordertab {
      width: calc(100vw - 140px);
    }
    .list-item {
      padding: 12px;
      .nullData {
        width: 50%;
        height: 50%;
      }
    }
    .wrapper {
      height: calc(100% - 30px);
      overflow: hidden;
    }
  }
}
</style>
